 <template>
  <d2-container>
    <!-- excel 导入 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogImportExcelVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      v-loading="isLoading"
      element-loading-text="后台正在处理中..."
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <el-row>
        <div class="d2-mb">
          <el-button @click="download">
            <d2-icon name="download" />下载导入模板
          </el-button>
        </div>
        <div class="d2-mb">
          <!-- <el-upload :before-upload="handleUpload" action="default">
            <el-button type="success">
              <d2-icon name="file-o"/>选择要导入的 .xls 表格
            </el-button>
          </el-upload>-->
          <el-upload
            ref="upload"
            action="http://39.107.237.7:10000/zuul/client/excelImport"
            :headers="{Authorization: _token}"
            :limit="1"
            :data="uploadParam"
            :auto-upload="false"
            :on-success="handleSuccess"
            :on-error="handleError"
          >
            <el-button size="medium" type="success">选择导入文件</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </div>
      </el-row>
      <!-- <el-row :gutter="20">
        <el-col :span="12">
          <el-checkbox v-model="isStrict">严格验证导入数据</el-checkbox>
        </el-col>
      </el-row>-->
      <el-row>
        <el-col :span="12">
          <el-input type="textarea" :rows="2" placeholder="请输入批次操作备注信息" v-model="batchRemarks"></el-input>
        </el-col>
      </el-row>
      <!-- <el-table v-bind="table" height="300px">
        <el-table-column
          v-for="(item, index) in table.columns"
          :key="index"
          :prop="item.prop"
          :label="item.label"
        ></el-table-column>
      </el-table>-->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importXls()" icon="el-icon-check" size="mini">确定导入</el-button>
      </div>
    </el-dialog>
    <!-- <loading :active="isLoading" :is-full-page="false"/> -->
    <!-- header 查询条件 -->
    <template slot="header">
      <el-form :inline="true" :model="listQuery" size="mini" style="margin-bottom: -18px;">
        <el-row>
          <el-col :span="24">
            <el-form-item style="float: left">
              <el-button @click="handleCreate" type="primary" icon="el-icon-plus">新 增</el-button>
              <!-- <el-button
                v-if="coustomer_batch_delete"
                @click="handleBatchDelete"
                type="primary"
                icon="el-icon-delete"
              >批量删除</el-button>-->

              <el-button
                v-if="customer_import"
                @click="showImportExcelDlg"
                type="primary"
                icon="fa fa-upload"
              >&nbsp;导入 Excel</el-button>
              <!-- <el-button
                v-if="customer_export"
                @click="exportExcel"
                type="primary"
                icon="fa fa-download"
              >&nbsp;导出 Excel</el-button>-->
              &nbsp;
              <el-select v-model="value" placeholder="请选择" v-if="coustomer_distribution">
                <el-option-group v-for="group in options" :key="group.label" :label="group.label">
                  <el-option
                    v-for="item in group.options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-option-group>
              </el-select>&nbsp;
              <el-button
                v-if="coustomer_distribution"
                @click="handleAssign"
                type="primary"
                icon="fa fa-paper-plane-o"
              >&nbsp;分配数据</el-button>&nbsp;
              <!-- <el-select v-model="value2" placeholder="请选择">
                <el-option
                  v-for="item in options2"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>&nbsp;
              <el-button @click="handleMove" type="primary" icon="fa fa-magic">&nbsp;移动数据</el-button>-->
              <!-- &nbsp;<el-date-picker v-model="reserveDateTime" type="datetime" placeholder="预约时间"></el-date-picker>
              &nbsp;
              <el-button
                @click="reserve"
                type="primary"
                icon="fa fa-clock-o"
              >&nbsp;预约</el-button>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="分类" prop="username">
          <el-select v-model="listQuery.client_type" placeholder="请选择">
            <el-option
              v-for="item in options3"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="已分配未分配" v-if="coustomer_distribution">
          <el-select v-model="listQuery.allocation" placeholder="请选择">
            <el-option
              v-for="item in options5"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车牌" prop="username">
          <el-input
            @keyup.enter.native="handleFilter"
            style="width: 200px;"
            placeholder
            v-model="listQuery.car_no"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="车主" prop="username">
          <el-input
            @keyup.enter.native="handleFilter"
            style="width: 200px;"
            placeholder
            v-model="listQuery.car_owner"
            clearable
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="被保险人" prop="username">
          <el-input
            @keyup.enter.native="handleFilter"
            style="width: 200px;"
            placeholder
            v-model="listQuery.insured"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="被保险人身份证" prop="username">
          <el-input
            @keyup.enter.native="handleFilter"
            style="width: 200px;"
            placeholder
            v-model="listQuery.insured_id_card"
            clearable
          ></el-input>
        </el-form-item>-->
        <el-form-item label="商业险到期日期" prop="username">
          <!-- <el-select v-model="listQuery.viEndDate" placeholder="请选择">
            <el-option
              v-for="item in options4"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>-->
          <el-date-picker
            v-model="listQuery.viEndDate"
            type="daterange"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="交强险到期日期" prop="username">
          <el-date-picker
            v-model="listQuery.clivtaEndDate"
            type="daterange"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="default" @click="handleFilter" icon="el-icon-search">搜 索</el-button>
        </el-form-item>
      </el-form>
    </template>
    <!-- table表格 -->
    <el-table
      ref="multipleTable"
      :key="tableKey"
      :data="list"
      @selection-change="handleSelectionChange"
      highlight-current-row
      stripe
      style="width: 100%;"
      sortable="true"
      :default-sort = "{prop: 'date', order: 'descending'}"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <!-- <el-table-column type="index" align="center" label="序号" width="60"></el-table-column> -->
      <el-table-column align="center" label="接收人" width="100" v-if="coustomer_distribution">
        <template slot-scope="scope">
          <span>{{scope.row.userName == null ? "未分配" : scope.row.userName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="车牌号" width="150">
        <template slot-scope="scope">
          <span>{{scope.row.carNo}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="车型" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.vehicleType}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="分类" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.label}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="车主" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.carOwner}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商业险到期日期" show-overflow-tooltip width="150" sortable prop="date">
        <template slot-scope="scope">
          <span>{{scope.row.viEndDate | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="交强险到期日期" show-overflow-tooltip width="150" sortable prop="date">
        <template slot-scope="scope">
          <span>{{scope.row.clivtaEndDate | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.note}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.modificationDate | parseTime('{y}-{m}-{d} {h}:{m}:{s}')}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="车架号" width="150">
        <template slot-scope="scope">
          <span>{{scope.row.vehicleNo}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发动机编号" show-overflow-tooltip width="150">
        <template slot-scope="scope">
          <span>{{scope.row.engineNumber}}</span>
        </template>
      </el-table-column>-->
      <!-- <el-table-column align="center" label="被保险人" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.insured}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="被保险人身份证" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.insuredIdCard}}</span>
        </template>
      </el-table-column>-->
      <!-- <el-table-column align="center" label="联系电话" show-overflow-tooltip width="150">
        <template slot-scope="scope">
          <span>{{scope.row.mobilePhone}}</span>
        </template>
      </el-table-column>-->
      <!-- <el-table-column align="center" label="联系电话2" show-overflow-tooltip width="150">
        <template slot-scope="scope">
          <span>{{scope.row.standbyMobile}}</span>
        </template>
      </el-table-column>-->
      <!-- <el-table-column align="center" label="续保日期" show-overflow-tooltip width="150">
        <template slot-scope="scope">
          <span>{{scope.row.modificationDate | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>-->

      <el-table-column align="center" label="创建时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.createDate | parseTime('{y}-{m}-{d} {h}:{m}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后一次通话时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.lastCallTime | parseTime('{y}-{m}-{d} {h}:{m}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="handleDetial(scope.row)"
            icon="fa fa-bar-chart"
          ></el-button>
          <el-button
            v-if="sys_user_upd"
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
            icon="el-icon-edit"
          ></el-button>
          <el-button
            v-if="sys_user_del"
            size="mini"
            type="danger"
            @click="deletes(scope.row)"
            icon="el-icon-delete"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- footer 分页条 -->
    <template slot="footer">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.page"
        :page-sizes="[50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: -10px;"
      ></el-pagination>
    </template>
    <!-- 新增客户信息弹框 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="80px" size="mini">
        <el-row style="width:100%">
          <el-col :span="12">
            <el-form-item label="分类" placeholder prop="carNo">
              <el-select v-model="value3" placeholder="请选择">
                <el-option
                  v-for="item in options3"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌" placeholder prop="carNo">
              <el-input v-model="form.carNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车架" placeholder prop="vehicleNo">
              <el-input v-model="form.vehicleNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发动机" placeholder prop="engineNumber">
              <el-input v-model="form.engineNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车主" placeholder prop="carOwner">
              <el-input v-model="form.carOwner"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="被保险人" placeholder prop="carOwner">
              <el-input v-model="form.insured"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" placeholder prop="carOwner">
              <el-input v-model="form.insuredIdCard"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" placeholder prop="mobilePhone">
              <el-input v-model="form.mobilePhone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话2" placeholder prop="standbyMobile">
              <el-input v-model="form.standbyMobile"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="初登日期" placeholder prop="firstRegistrationDate">
              <el-date-picker
                v-model="form.firstRegistrationDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交强日期" placeholder prop="firstRegistrationDate">
              <el-date-picker
                v-model="form.clivtaEndDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商业日期" placeholder prop="firstRegistrationDate">
              <el-date-picker
                v-model="form.viEndDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')" icon="el-icon-close" size="mini">取 消</el-button>
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          @click="create('form')"
          icon="el-icon-check"
          size="mini"
        >确 定</el-button>
        <el-button
          v-else
          type="primary"
          @click="update('form')"
          icon="el-icon-check"
          size="mini"
        >修 改</el-button>
      </div>
    </el-dialog>
  </d2-container>
</template>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  getTreeData,
  importData,
  getAassignList,
  assignData,
  batchDelObj,
  insertBookingByClientId,
  batchMoveSellData
} from "@/api/customer";

import * as callcenter from "@/api/callcenter";
import * as newcomer from "@/api/newcomer";

import { deptRoleList, fetchDeptTree } from "@/api/role";
import { mapGetters, mapState } from "vuex";
import ElRadioGroup from "element-ui/packages/radio/src/radio-group";
import ElOption from "element-ui/packages/select/src/option";
// Import component
import Loading from "vue-loading-overlay";
// Import stylesheet
import "vue-loading-overlay/dist/vue-loading.css";

import util from "@/libs/util";

export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
}

function padLeftZero(str) {
  return ("00" + str).substr(str.length);
}

export default {
  name: '客户列表',
  components: {
    ElOption,
    ElRadioGroup,
    Loading
  },
  data() {
    return {
      myHeaders: {},
      uploadParam: {},
      batchRemarks: null,
      isStrict: true,
      reserveDateTime: null,
      // 分配数据
      options: [],
      value: "",
      // 移动数据
      options2: [],
      value2: "",
      // 分类
      options3: [],
      value3: "",
      // 已分配未分配
      options5: [
        {
          label: "所有",
          value: -1
        },
        {
          label: "已分配",
          value: 1
        },
        {
          label: "未分配",
          value: 0
        }
      ],

      // 续保日期
      options4: [
        {
          value: "-1",
          label: "所有"
        },
        {
          value: "30",
          label: "30天"
        },
        {
          value: "60",
          label: "60天"
        },
        {
          value: "90",
          label: "90天"
        }
      ],
      value4: "",
      props: {
        label: "name",
        children: "zones"
      },
      count: 1,
      filename: __filename,
      table: {
        columns: [],
        data: [],
        size: "mini",
        stripe: true,
        border: true
      },
      callList: null,
      isLoading: false,
      treeDeptData: [],
      checkedKeys: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      list: null,
      total: null,
      listQuery: {
        page: 1,
        limit: 50,
        car_owner: null,
        car_no: null,
        client_type: null,
        insEndDate: null
      },
      form: {
        carNo: undefined,
        vehicleNo: undefined,
        engineNumber: undefined,
        carOwner: undefined,
        mobilePhone: undefined,
        vehicleType: undefined,
        firstRegistrationDate: undefined
      },
      rules: {},
      statusOptions: ["0", "1"],
      rolesOptions: [],
      dialogFormVisible: false,
      dialogDetailVisible: false,
      dialogDeptVisible: false,
      dialogImportExcelVisible: false,
      dialogAssignVisible: false,
      userAdd: false,
      userUpd: false,
      userDel: false,
      dialogStatus: "",
      textMap: {
        update: "编辑客户信息",
        create: "新增客户信息",
        import: "导入业务数据",
        assign: "分配业务数据"
      },
      isDisabled: {
        0: false,
        1: true
      },
      tableKey: 0,
      multipleSelection: []
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: "有效",
        1: "无效",
        9: "锁定"
      };
      return statusMap[status];
    }
  },
  computed: {
    // ...mapGetters(['permissions']),
    ...mapState("d2admin/user", ["info"]),
    _token: {
      get: function() {
        return "Bearer " + util.cookies.get("token");
      }
    }
  },
  created() {
    console.log(this.$route.name)
    this.sys_user_add = this.hasFunctions(["sys_user_add"]);
    this.sys_user_upd = this.hasFunctions(["sys_user_upd"]);
    this.sys_user_del = this.hasFunctions(["sys_user_del"]);

    this.customer_import = this.hasFunctions(["customer_import"]);
    this.customer_export = this.hasFunctions(["customer_export"]);
    this.coustomer_delete = this.hasFunctions(["coustomer_delete"]);
    this.coustomer_batch_delete = this.hasFunctions(["coustomer_batch_delete"]);
    this.coustomer_distribution = this.hasFunctions(["coustomer_distribution"]);

    getAassignList().then(resp => {
      console.log(resp);
      this.options = resp.result;
    });

    newcomer.queryDictListByType("clientGrouping").then(resp => {
      console.log(resp);
      this.options2 = resp;
    });

    newcomer.queryDictListByType("clientType").then(resp => {
      console.log(resp);
      this.options3 = resp.records;
    });

      let paths = this.$route.path.split('/')
      let _success = paths[paths.length-1]
      this.listQuery.success = _success;
    // if (_success != undefined) {
    //   this.listQuery.success = _success;
    //   this.$route.meta.title = this.$route.query.title;
    // } else this.$route.meta.title = "客户列表";

    this.getList();
  },
  methods: {
    handleSuccess(response, file, fileList) {
      this.isLoading = false;
      console.log("文件上传 success");

      if (response.status == "SUCCEED") {
        this.$message({
          type: "success",
          message: response.extMessage
        });

        this.batchRemarks = response.extMessage + "\r\n" + response.result.repeat;
      } else {
        this.$message({
          type: "error",
          message: response.errorMessage
        });
      }
    },

    handleError(err, file, fileList) {
      this.isLoading = false;
      console.log("文件上传 error");
      this.$message({
        type: "error",
        message: "导入文件失败"
      });
    },

    reserve() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: "error",
          message: "请选择一条预约数据"
        });
        return;
      }

      if (this.multipleSelection.length > 1) {
        this.$message({
          type: "error",
          message: "预约数据，只能单选！"
        });
        return;
      }

      let newDt = formatDate(this.reserveDateTime, "yyyy-MM-dd hh:mm:ss");
      insertBookingByClientId({
        clientId: this.multipleSelection[0].id,
        bookingTime: newDt
      }).then(resp => {
        console.log(resp);
        if (resp.status == "SUCCEED") {
          this.$message({
            type: "success",
            message: "预约成功"
          });
        } else {
          this.$message({
            type: "error",
            message: "预约失败"
          });
        }
      });
    },

    handleMove() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: "error",
          message: "请选择要操作的数据"
        });
        return;
      }

      let ids = [];
      this.multipleSelection.forEach(element => {
        ids.push(element.id);
      });

      // clientGrouping1
      // {ids: [], status: 'clientGrouping1'}
      batchMoveSellData({ ids: ids, status: this.value2 }).then(resp => {
        console.log(resp);
        if (resp.status == "SUCCEED") {
          this.$message({
            type: "success",
            message: "操作成功"
          });

          this.getList();
        } else {
          this.$message({
            type: "error",
            message: "操作失败"
          });
        }
      });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleBatchDelete() {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let ids = [];
        this.multipleSelection.forEach(element => {
          ids.push(element.id);
        });

        batchDelObj(ids).then(resp => {
          console.log(resp);
          this.$message({
            type: "success",
            message: "删除成功"
          });

          this.getList();
        });
      });
    },

    importXls() {
      // {"isValidate":"","remark":"","list":[]}
      // let input = {
      //   list: this.table.data,
      //   isValidate: this.isStrict == true ? 1 : 0,
      //   remark: this.batchRemarks
      // };

      // importData(input).then(resp => {
      //   console.log(resp);
      //   this.isLoading = false;

      //   if (resp.status == "SUCCEED") {
      //     this.$confirm(resp.result, "提示", {
      //       confirmButtonText: "确定",
      //       showCancelButton: false,
      //       type: "success"
      //     });
      //   } else
      //     this.$message({
      //       type: "error",
      //       message: resp.errorMessage
      //     });
      // });

      if (this.$refs.upload.uploadFiles.length == 0) {
        this.$message({
          type: "error",
          message: "先选择文件后，才能点击确认导入！"
        });
        return;
      }

      this.uploadParam.isValidate = 0;
      this.uploadParam.remark = this.batchRemarks;

      this.$refs.upload.submit();
      this.isLoading = true;
    },

    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    handleNodeClick(data) {
      console.log(data);
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ name: "region1" }, { name: "region2" }]);
      }
      if (node.level > 3) return resolve([]);

      var hasChild;
      if (node.data.name === "region1") {
        hasChild = true;
      } else if (node.data.name === "region2") {
        hasChild = false;
      } else {
        hasChild = Math.random() > 0.5;
      }

      setTimeout(() => {
        var data;
        if (hasChild) {
          data = [
            {
              name: "zone" + this.count++
            },
            {
              name: "zone" + this.count++
            }
          ];
        } else {
          data = [];
        }

        resolve(data);
      }, 500);
    },

    handleUpload(file) {
      this.$import.xlsx(file).then(({ header, results }) => {
        this.table.columns = header.map(e => {
          return {
            label: e,
            prop: e
          };
        });
        this.table.data = results;
      });
      return false;
    },

    download() {
      window.location.href =
        "http://media.avicyt.com/%E8%BD%A6%E8%BE%86%E4%BF%A1%E6%81%AF%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF1.0.xls";
    },

    showImportExcelDlg() {
      this.dialogStatus = "import";
      this.dialogImportExcelVisible = true;
      this.table.columns = [];
      this.table.data = [];
    },

    exportExcel() {
      window.location.href =
        "http://media.avicyt.com/%E8%BD%A6%E8%BE%86%E4%BF%A1%E6%81%AF%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls";
    },

    getList() {
      this.isLoading = true;
      this.listQuery.isAsc = false;
      fetchList(this.listQuery).then(response => {
        this.list = response.records;
        this.total = response.total;
        this.isLoading = false;
      });
    },
    getNodeData(data) {
      this.dialogDeptVisible = false;
      this.form.deptId = data.id;
      this.form.deptName = data.name;
      deptRoleList(data.id).then(response => {
        this.rolesOptions = response;
      });
    },
    handleDept() {
      fetchDeptTree().then(response => {
        this.treeDeptData = response;
        this.dialogDeptVisible = true;
      });
    },
    handleFilter() {
      let tmp = this.listQuery.viEndDate;
      if(tmp != undefined) {
        this.listQuery.viEndDate = tmp[0];
        this.listQuery.viEndDateEnd = tmp[1];
      }

      tmp = this.listQuery.clivtaEndDate;
      if(tmp != undefined) {
        this.listQuery.clivtaEndDate = tmp[0];
        this.listQuery.clivtaEndDateEnd = tmp[1];
      }

      this.listQuery.page = 1;

      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      // deptRoleList(this.info.deptId).then(response => {
      //   this.rolesOptions = response.data
      // })
    },
    handleAssign() {
      if (this.value == "") {
        this.$message({
          type: "error",
          message: "请选择分配对象"
        });
        return;
      }

      this.$confirm("确认分配么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let clientIds = [];
        this.multipleSelection.forEach(element => {
          clientIds.push(element.id);
        });

        let input = {
          userId: this.value,
          clientIds: clientIds
        };
        assignData(input).then(resp => {
          console.log(resp);
          this.getList();
        });
      });
    },
    handleUpdate(row) {
      this.form = row;
      this.dialogFormVisible = true;
      this.dialogStatus = "update";
    },
    create(formName) {
      const set = this.$refs;
      this.form.role = this.role;
      set[formName].validate(valid => {
        if (valid) {
          this.form.userId = this.info.id;

          addObj(this.form).then(resp => {
            if (resp.response != undefined && resp.response.data.extMessage.indexOf("Duplicate") > 0) {
              this.$notify({
                title: "提示",
                message: "车牌号重复，联系主管重新分配数据",
                type: "error"
              });
              return;
            }

            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "提示",
              message: "创建成功",
              type: "success"
            });
          });
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      this.dialogAssignVisible = false;
      this.$refs[formName].resetFields();
    },

    update(formName) {
      const set = this.$refs;
      // this.form.role = this.role
      console.log(this.form);
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false;
          this.form.password = undefined;

          this.form.clientType = this.value3;
          this.form.mobilePhone = null;
          this.form.standbyMobile = null;

          putObj(this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },

    deletes(row) {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delObj(row.id)
          .then(() => {
            this.getList();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
          })
          .cache(() => {
            this.$notify({
              title: "失败",
              message: "删除失败",
              type: "error",
              duration: 2000
            });
          });
      });
    },

    handleDetial(row) {
      if (row.firstRegistrationDate != null)
        row.firstRegistrationDate = row.firstRegistrationDate.split(" ")[0];

      this.$router.push({
        path: "/customer/detail",
        query: { id: row.id, clientName: row.carOwner, obj: row }
      });
    },

    resetTemp() {
      this.form = {
        id: undefined,
        username: "",
        password: "",
        roleList: [],
        delFlag: "",
        deptId: "",
        phone: ""
      };
    }
  },
  watch: {
    '$route' (to, from) {
      console.log(this.$route.name)
      this.sys_user_add = this.hasFunctions(["sys_user_add"]);
      this.sys_user_upd = this.hasFunctions(["sys_user_upd"]);
      this.sys_user_del = this.hasFunctions(["sys_user_del"]);

      this.customer_import = this.hasFunctions(["customer_import"]);
      this.customer_export = this.hasFunctions(["customer_export"]);
      this.coustomer_delete = this.hasFunctions(["coustomer_delete"]);
      this.coustomer_batch_delete = this.hasFunctions(["coustomer_batch_delete"]);
      this.coustomer_distribution = this.hasFunctions(["coustomer_distribution"]);

      getAassignList().then(resp => {
        console.log(resp);
        this.options = resp.result;
      });

      newcomer.queryDictListByType("clientGrouping").then(resp => {
        console.log(resp);
        this.options2 = resp;
      });

      newcomer.queryDictListByType("clientType").then(resp => {
        console.log(resp);
        this.options3 = resp.records;
      });

      let paths = this.$route.path.split('/')
      let _success = paths[paths.length-1]
      this.listQuery.success = _success
      // if (_success != undefined) {
      //   this.listQuery.success = _success;
      //   this.$route.meta.title = this.$route.query.title;
      // } else this.$route.meta.title = "客户列表";

      this.getList();
    }
  }
};
</script>
<style lang="scss" scoped>
.d2-mb {
  float: left;
  margin-right: 20px;
}
.d2-mb .el-button i {
  margin-right: 4px;
}

.el-row {
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 0;
  }
}
</style>
